//package org.example.deviceManagement;
package com.scau.os.deviceManagement;
import com.scau.os.course_manager.bean.PCB;
import com.scau.os.extension.EventSystem;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;


public class DeviceUse {
    public static Map<String, Peripheral> peripherals =new HashMap<>();
    static {
        peripherals.put("A1",new PeripheralA("A1"));
        peripherals.put("A2",new PeripheralA("A2"));
        peripherals.put("B1",new PeripheralB("B1"));
        peripherals.put("B2",new PeripheralB("B2"));
        peripherals.put("B3",new PeripheralB("B3"));
        peripherals.put("C1",new PeripheralC("C1"));
        peripherals.put("C2",new PeripheralC("C2"));
        peripherals.put("C3",new PeripheralC("C3"));
    }
    private int interval;
    public static Map<String,PCB> Process =  new HashMap<>();//能够正常运行的进程对应的PCB和使用的设备名称放在这里



    public boolean resetPeripheral(String peripheralName){
        boolean isok = false;
        for (String i: peripherals.keySet()){
            if (peripheralName.equals(i)){
                Peripheral peripheral = peripherals.get(i);
                peripheral.reset();
            }
        }
        return isok;
    }
    /**
     *分配设备
     */
    public boolean allocatePeripheral(String peripheralName, int time,PCB pcb){

        boolean isok = false;
        for (String i: peripherals.keySet()){
            if (i.contains(peripheralName)){

                if (peripherals.get(i).getStatus()==0) {
                    isok = peripherals.get(i).allocate(time);
                    Process.put(peripheralName,pcb);
                    break;
                }
                else if (peripherals.get(i).getStatus()==127){
                    isok = false;
                    System.out.println(i+"已经被使用");
                    break;
                }
            }
        }
        EventSystem.instance.SendEvent("RefreshPeripheral", peripheralName);

//        DeviceExecute.executePeripheral(peripheralName);

        return isok;
    }
    /**
     * 该方法用于返回设备的状态，当cpu需要更新设备的状态的时候，通过这个方法来获取
     * 设备的状态
     */
    public int getPeripheralStatus(String deviceName){

        int status=0;
        boolean found = false;
        for (String i: peripherals.keySet()){
            if (i.contains(deviceName)){
                found = true;
                Peripheral peripheral = peripherals.get(i);
                int new_status = peripheral.getStatus();
                if (new_status==-1){
                    status=-1;
                    peripheral.reset();//中断解除
                    return status;
                }
                if (new_status==0){
                    status=0;
                    return status;
                }
            }
        }
//        if (found) return status;
//        else return null;
        return status;
    }
}
